package cn.tedu._03vehicle.base.Exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult doHandle(IllegalArgumentException e ){

        String data = e.getMessage();

        log.error("IllegalArgumentException" + data);

        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    @ExceptionHandler(RuntimeException.class)
    public JsonResult doHandle(RuntimeException e ){
        String data = e.getMessage();
        log.error("RuntimeException" + data);
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    @ExceptionHandler(Throwable.class)
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        log.error("Throwable:" + data);
        return new JsonResult(StatusCode.THROWABLE_ERROR, data);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:" + data);
        return new JsonResult(StatusCode.VALIDATRD_ERROR, data);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + data);
        return new JsonResult(StatusCode.VALIDATRD_ERROR, data);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult doHandleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex){
        String data = "文件大小超出限制";
        log.error("MaxUploadSizeExceededException:" + data);
        return new JsonResult(StatusCode.FILE_IS_SO_BIG, data);
    }

}
